package threecard.android;
import threecard.android.httpHelper.AccountDbHelper;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Settings extends MainActivity {
	// Game preference values
	SharedPreferences mGameSettings;//key-value
    static final int EMAIL_DIALOG_ID = 0;
    static final int PASSWORD_DIALOG_ID = 1;
   //attribute before settings new infor
    private String mNewPwd;
    private String mOldPwd;
    private String mNewEmail;//new email
    private String mUsername;
    final String DEBUG ="SETTINGS DEBUG";
    private boolean mPwdChangeable = false;
    private boolean mEmailChangeable = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
     
        mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
        mUsername = mGameSettings.getString(GAME_PREFERENCES_USERNAME, "Not set");
        mOldPwd = mGameSettings.getString(GAME_PREFERENCES_PASSWORD, "Not set");
             
        // Initialize the Password chooser
        initPasswordChooser();
        initEmailChooser();
        //change password to md5 type  before changing it
        resetPassword(mUsername,mOldPwd, mPwdChangeable,mNewPwd);
        resetEmail(mUsername,mOldPwd,mEmailChangeable,mNewEmail);
    }
    // change if mEmailChangeable = true;
  //send new info to server to reset info
  		//receive result and change SharedPreference if success
	private void resetEmail(String username, String password,
			boolean changeable, String newEmail) {
		// TODO Auto-generated method stub
		Log.i(DEBUG,"change email: "+username+", "+password+", "+newEmail);
		if (changeable == false) return;
		AccountDbHelper account = new AccountDbHelper(username,password);
	 	boolean result = account.actionChangeEmail(newEmail);
	 	if (result == true){
	 		createDialog("SUCCESS","Changed email"); 
	 	}else{
	 		createDialog("Fail","Sorry!! Cannot change email"); 
	 	}
	}
	/*
	 *  change if mPwdChangeable = true; send new info to server to reset info
	 *  receive result and change SharedPreference if success
	 */
	private void resetPassword(String username, String password,
			boolean changeable, String  newPwd){
		Log.i(DEBUG,"change email: "+username+", "+password+", "+newPwd);
		if (changeable == false) return;
		//change email
		AccountDbHelper account = new AccountDbHelper( username, password);
	 	boolean result = account.actionChangePassword( newPwd);
	 	if (result == true){
	 		createDialog("SUCCESS","Changed password");
	 		//get shared preference and save it
	 		mOldPwd = newPwd;
			Editor editor = mGameSettings.edit();
            editor.putString(GAME_PREFERENCES_USERNAME, username);
            editor.putString(GAME_PREFERENCES_PASSWORD, newPwd);
            editor.commit();
	 	}else{
	 		createDialog("Fail","Sorry!! Cannot change password"); 
	 	}
	}

	@Override
    protected void onDestroy() {
        Log.d(DEBUG_TAG, "SHARED PREFERENCES");
        Log.d(DEBUG_TAG, "Email is: " + mGameSettings.getString(GAME_PREFERENCES_EMAIL, "Not set"));
        Log.d(DEBUG_TAG, "Username is: " + mGameSettings.getString(GAME_PREFERENCES_USERNAME, "Not set"));
        Log.d(DEBUG_TAG, "Password is: " + mGameSettings.getString(GAME_PREFERENCES_PASSWORD, "Not set"));
        super.onDestroy();
    }

   
    /**
     * Initialize the Password chooser
     */
    private void initPasswordChooser() {
        // Set password info
        TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
        if (mGameSettings.contains(GAME_PREFERENCES_PASSWORD)) {
            passwordInfo.setText(R.string.settings_pwd_set);
        } else {
            passwordInfo.setText(R.string.settings_pwd_not_set);
        }
        // Handle password setting dialog
        Button setPassword = (Button) findViewById(R.id.Button_Password);
        setPassword.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(PASSWORD_DIALOG_ID);
            }
        });
    }
    
    /**
     * Initialize the Password chooser
     */
    private void initEmailChooser() {
        // Set password info
        TextView emailInfo = (TextView) findViewById(R.id.TextView_Password_Info);//TextView_Email_Info
        if (mGameSettings.contains(GAME_PREFERENCES_EMAIL)) {
        	emailInfo.setText(R.string.settings_valid_email);
        } else {
        	emailInfo.setText(R.string.settings_invalid_email);
        }
        // Handle password setting dialog
        Button setEmail = (Button) findViewById(R.id.Button_Email);
        setEmail.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(EMAIL_DIALOG_ID);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PASSWORD_DIALOG_ID:
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View layout = inflater.inflate(R.layout.pwd_dialog, (ViewGroup) findViewById(R.id.root));
            final EditText p = (EditText) layout.findViewById(R.id.settings_EditText_oldPwd);
            final EditText p1 = (EditText) layout.findViewById(R.id.settings_EditText_Pwd1);
            final EditText p2 = (EditText) layout.findViewById(R.id.settings_EditText_Pwd2);
            final TextView error = (TextView) layout.findViewById(R.id.settings_TextView_PwdProblem);
            p2.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
//                	String confirmPwd = p.getText().toString();
                    String strPass1 = p1.getText().toString();
                    String strPass2 = p2.getText().toString();
                    
                    if (strPass1.equals(strPass2)) {
                        error.setText(R.string.settings_pwd_equal);
                    } else {
                        error.setText(R.string.settings_pwd_not_equal);
                    }
                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(layout);
            // Now configure the AlertDialog
            builder.setTitle(R.string.settings_button_pwd);
            builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again (no cached info)
                    Settings.this.removeDialog(PASSWORD_DIALOG_ID);
                }
            });
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
//                    TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
                    String confirmPassword = md5(p.getText().toString());
                    String strPassword1 = p1.getText().toString();
                    String strPassword2 = p2.getText().toString();
                   
                    if (strPassword1.equals(strPassword2) && confirmPassword.equals(mOldPwd)) {
                    	mNewPwd = md5(strPassword2);
                    	mPwdChangeable = true;
                    	Log.d(DEBUG, "New password is: " + mNewPwd);
                    } else {
                        Log.d(DEBUG_TAG, "Passwords do not match. Not saving. Keeping old password (if set).");
                    }
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again
                    Settings.this.removeDialog(PASSWORD_DIALOG_ID);
                }
            });
            // Create the AlertDialog and return it
            AlertDialog passwordDialog = builder.create();
            return passwordDialog;
      
            case EMAIL_DIALOG_ID:
            LayoutInflater inflater_email = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View layout_email = inflater_email.inflate(R.layout.email_dialog, (ViewGroup) findViewById(R.id.root));
            final EditText oldPwd = (EditText) layout_email.findViewById(R.id.settings_email_EditText_oldPwd);
            final EditText newEmail = (EditText) layout_email.findViewById(R.id.settings_EditText_email);
            final TextView error_email = (TextView) layout_email.findViewById(R.id.settings_TextView_EmailProblem);
            newEmail.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                    
                    if (isEmailAddress(mNewEmail) ){
                    	error_email.setText(R.string.settings_valid_email);
                   
                    }else{
                    	error_email.setText(R.string.settings_invalid_email);
                    }
                }
				@Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            AlertDialog.Builder builder_email = new AlertDialog.Builder(this);
            builder_email.setView(layout_email);
            // Now configure the AlertDialog
            builder_email.setTitle(R.string.settings_email);
            builder_email.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again (no cached info)
                    Settings.this.removeDialog(EMAIL_DIALOG_ID);
                }
            });
            builder_email.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
//                    TextView emailInfo = (TextView) findViewById(R.id.TextView_Password_Info);
                    String confirmPwd = md5(oldPwd.getText().toString());
                    
                    if (confirmPwd.equals(mOldPwd)){
                    	mEmailChangeable = true;
                    	mNewEmail = newEmail.getText().toString();
                    	Log.i(DEBUG,"Change to new email: "+mNewEmail);
                    }else {
                    	mEmailChangeable = false;
                    	Log.i(DEBUG,"Cannot change to new email cause of wrong password: "+mNewEmail);
                    }
                    // We forcefully dismiss and remove the Dialog, so it
                    // cannot be used again
                    Settings.this.removeDialog(EMAIL_DIALOG_ID);
                }
            });
            // Create the AlertDialog and return it
            AlertDialog emailDialog = builder_email.create();
            return emailDialog;
          //   */
            default: break;
        }
        return null;
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        switch (id) {
        
        case PASSWORD_DIALOG_ID:
            // Handle any Password Dialog initialization here
            // Since we don't want to show old password dialogs, just set new
            // ones, we need not do anything here
            // Because we are not "reusing" password dialogs once they have
            // finished, but removing them from
            // the Activity Dialog pool explicitly with removeDialog() and
            // recreating them as needed.
            return;
        case EMAIL_DIALOG_ID:
            // Handle any Password Dialog initialization here
            // Since we don't want to show old password dialogs, just set new
            // ones, we need not do anything here
            // Because we are not "reusing" password dialogs once they have
            // finished, but removing them from
            // the Activity Dialog pool explicitly with removeDialog() and
            // recreating them as needed.
            return;
          default: break;
        }
    }
}
